import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import routes from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import session from '@/utils/session'
import constant from '@/utils/constant'

Vue.use(VueRouter)

const router = new VueRouter({
    routes,
    mode: 'history'
})

const Login = constant.ConstantRouteName.Login;
const Home = constant.ConstantRouteName.Home;
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const toRoute = to.name;
    let noLoginFlag = true;
    let accessToken = session.getAccessToken();
    if (accessToken) {
        if (toRoute == Login) {
            // 已登录访问登录页面
            next({name: Home});
            NProgress.done();
        } else {
            try {
                const roles = store.getters.roles;
                if(roles && roles.length > 0) {
                    next();
                } else {
                    await store.dispatch('auth/getUserInfo');
                    await store.dispatch('main/createRoutes').then(({routes, dynRoutes}) => {
                        router.addRoutes(dynRoutes);
                    });
                    // 已登录访问不是登录页面
                    next({ ...to, replace: true });
                }
            } catch (err) {
                // 未登录访问的不是登录页面
                Vue.prototype.$MessageN.error(err);
                session.removeToken();
                store.commit('auth/remove');
                NProgress.done();
            }
        }
    } else {
        if (!accessToken && toRoute == Login) {
            // 未登录访问的登录页面
            next();
        } else if (!accessToken && toRoute != Login) {
            // 未登录访问的不是登录页面
            next({name: Login});
            NProgress.done();
        }
    }
});

router.afterEach((to, from) => {
    NProgress.done();
});

export default router;

